package com.impress;

import java.util.ArrayList;
import java.util.List;

import com.guohead.sdk.GuoheAdLayout;
import com.guohead.sdk.GuoheAdManager;
import com.impress.adapter.BriefItemsAdapter;
import com.impress.adapter.FeedListAdapter;
import com.impress.model.AccountPreference;
import com.impress.model.Feed;
import com.impress.model.Item;
import com.impress.service.FeedService;
import com.impress.service.ItemService;
import com.mobclick.android.MobclickAgent;
import com.mobclick.android.ReportPolicy;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Gallery;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainListActivity extends Activity {

	private TitleBar titleBar;
	private Gallery mFeedGallery;
	private Gallery mItemGallery;
	
	private ItemService mItemService = new ItemService(this);
	private FeedListAdapter mFeedAdapter;
	private BriefItemsAdapter mItemsAdapter;
	
	private static Object locker = new Object();
	private boolean isRefreshing;
	
	private int mSelectedFeed;
	
	public static final int VIEW_DETAILS = 1;
	private static final int DIALOG_EXIT_APP = 0;
	public static final int MARK_ALL_AS_READ = DIALOG_EXIT_APP+1;
	private Feed mFeed;
	
	private List<Feed> mFeeds;
	private boolean mUnReadOnly = true;
	private boolean scheduleChange = false;
	
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			try {
				String intentAction = intent.getAction();
				if (TextUtils.equals(intentAction, SyncService.NOTIFY_CHANGE)) {
					boolean uploadChange = intent.getBooleanExtra(SyncService.UPLOAD_FINISH, false);
					if (uploadChange) {
						scheduleChange = false;
					}else {
						setGallery();
						mFeedGallery.setSelection(0);
						titleBar.setProgressBarVisible(false);
						isRefreshing = false;
					}
				}else if (TextUtils.equals(intentAction, SyncService.NOTIFY_LOGIN)) {
					startActivity(new Intent(MainListActivity.this, AccountLogin.class));
				}
				
				
			} catch (Exception e) {
				Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
//				Log.e(TAG, e.getMessage());
			}
			
		}
	};
	
	private final BroadcastReceiver removeItemsReceiver = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			int selectedPosition = intent.getIntExtra(FeedListAdapter.SELECTED_POSITION, 0);
			if(mFeeds == null || mFeeds.size() == 0){
				mItemsAdapter.clear();
			}else{
				if(selectedPosition>=mFeeds.size()){
					mItemsAdapter.mItems = mFeeds.get(mFeeds.size()-1).items;
				}else{
					mItemsAdapter.mItems = mFeeds.get(selectedPosition).items;					
				}
			}
			mItemsAdapter.notifyDataSetChanged();
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {		
		super.onCreate(savedInstanceState);
		
		MobclickAgent.onError(this);
		MobclickAgent.setReportPolicy(ReportPolicy.DAILY);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main);
		IntentFilter filter = new IntentFilter(SyncService.NOTIFY_CHANGE);
		filter.addAction(SyncService.NOTIFY_LOGIN);
		registerReceiver(mReceiver, filter);
		IntentFilter removeItemFilter = new IntentFilter(FeedListAdapter.REMOVE_ITEMS);
		registerReceiver(removeItemsReceiver, removeItemFilter);
		
		RelativeLayout.LayoutParams AdLayoutParams = new RelativeLayout.LayoutParams(
				LayoutParams.FILL_PARENT, 
				LayoutParams.WRAP_CONTENT); 
		LinearLayout footer = (LinearLayout)findViewById(R.id.adView);
		GuoheAdLayout adLayout = new GuoheAdLayout(this);
		footer.addView(adLayout,AdLayoutParams);
		
		titleBar = (TitleBar)findViewById(R.id.titlebar);
		titleBar.setViewState(Utility.VIEW_STATE_FEED);
		titleBar.setRefreshListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				refreshItem();
				return false;
			}
		});
		mFeedGallery = (Gallery)findViewById(R.id.gallery);
		mItemGallery = (Gallery)findViewById(R.id.item_gallery);
		
		mFeeds = new ArrayList<Feed>();
		mFeedAdapter = new FeedListAdapter(this, mFeeds);
		mFeedGallery.setAdapter(mFeedAdapter);
		mFeedGallery.setCallbackDuringFling(false);
		mFeedGallery.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				Feed feed = (Feed)mFeedAdapter.getItem(position);
				mItemsAdapter.mItems = feed.items;
				mItemsAdapter.notifyDataSetChanged();
				mSelectedFeed = position;
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub
				
			}
		});
		
		mItemsAdapter = new BriefItemsAdapter(this, new ArrayList<Item>());
		mItemGallery.setAdapter(mItemsAdapter);
		mItemGallery.setCallbackDuringFling(false);
		
		mItemGallery.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Bundle bundle = new Bundle();
				ArrayList list = new ArrayList();
				list.add(mItemsAdapter.mItems);
				bundle.putParcelableArrayList("list", list);
				bundle.putInt("selectedItem", position);
				Intent intent = new Intent();
				intent.putExtras(bundle);
				intent.setClass(MainListActivity.this, ItemsViewActivity.class);
				startActivityForResult(intent, VIEW_DETAILS);
			}
		});
		
		TextView emptyFeedView = (TextView)findViewById(R.id.emptyFeed);
		emptyFeedView.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				refreshItem();
				return false;
			}
		});
		mFeedGallery.setEmptyView(findViewById(R.id.emptyFeed));
		mItemGallery.setEmptyView(findViewById(R.id.empty));
		
		setGallery();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {		
		super.onActivityResult(requestCode, resultCode, data);
		int selected = data.getIntExtra("selectedItem", 0);
		setGallery();
		if(mFeeds == null || mFeeds.isEmpty()){
			return;
		}
		selected = mSelectedFeed;
		if(mFeeds.size()<=selected){
			selected = mFeeds.size()-1;
		}
		mFeedGallery.setSelection(selected);
		mItemsAdapter.mItems = mFeeds.get(selected).items;
		mItemsAdapter.notifyDataSetChanged();
	}

	@Override
	protected void onDestroy() {
		unregisterReceiver(mReceiver);
		unregisterReceiver(removeItemsReceiver);
		GuoheAdManager.finish(this);
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.clear();
		getMenuInflater().inflate(R.menu.main_options_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		MenuItem refreshItem = menu.findItem(R.id.refresh_menu_item);
        if (titleBar.getRefreshButtonVisibility() == View.GONE) {
                refreshItem.setVisible(false);

        }else {
                refreshItem.setVisible(true);
        }
        //when refreshing items, clear cache and log out should not been visible
        menu.findItem(R.id.stop_refresh_menu_item).setVisible(!refreshItem.isVisible());
        menu.findItem(R.id.clearcache_menu_item).setVisible(refreshItem.isVisible());
        menu.findItem(R.id.logout_menu_item).setVisible(refreshItem.isVisible());

        //set to show unread or all article.
        menu.findItem(R.id.show_all_menu_item).setVisible(mUnReadOnly);
        menu.findItem(R.id.unread_only_menu_item).setVisible(!mUnReadOnly);

		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
        //refresh
        case R.id.refresh_menu_item:
                refreshItem();
                break;
        //stop refresh
        case R.id.stop_refresh_menu_item:
                stopService(new Intent(this, SyncService.class));
                titleBar.setProgressBarVisible(false);
                break;
        //clear cache
        case R.id.clearcache_menu_item:
                mItemService.clearCache();
                clearGallery();
                break;
        //log out->clear cache first.
        case R.id.logout_menu_item:
                mItemService.clearCache();
                clearGallery();
                AccountPreference accountPreference = new AccountPreference(this);
                accountPreference.accountLogOut();
                startActivity(new Intent(this, AccountLogin.class));
                break;
        case R.id.show_all_menu_item:
                toggleArticles(false);
                break;
        case R.id.unread_only_menu_item:
                toggleArticles(true);
                break;
        case R.id.send_feedback_menu_item:
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"pluto_y-3@hotmail.com"});
                intent.putExtra(Intent.EXTRA_SUBJECT, getText(R.string.feedbackTitle));
                intent.setType("message/rfc822");
                startActivity(Intent.createChooser(intent, getText(R.string.emailChooserTitle)));
                break;
		}
		return super.onOptionsItemSelected(item);
	}

	
	public void showDialog(int id, Feed feed,int position){
		mFeed = feed;
		mSelectedFeed = position;
		showDialog(id);
	}
	
    @Override
    protected Dialog onCreateDialog(int id) {
            // TODO Auto-generated method stub
            Dialog dialog = null;
            dialog = createDialog(id);
            return dialog;
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
            // TODO Auto-generated method stub
            super.onPrepareDialog(id, dialog);
    }
    
    private Dialog createDialog(int id){
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            switch (id) {
            case DIALOG_EXIT_APP:
                    builder.setTitle(R.string.exitDialogTitle);
                    builder.setMessage(R.string.exitDialogMessage);
                    builder.setPositiveButton(R.string.exitDialogPositive, new OnClickListener() {
                            
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                    // TODO Auto-generated method stub
                                    dialog.dismiss();
                                    MainListActivity.this.finish();
                            }
                    });
                    builder.setNegativeButton(R.string.exitDialogNegative, new OnClickListener() {
                            
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                    // TODO Auto-generated method stub
                                    dialog.dismiss();
                            }
                    });
                    break;
            case MARK_ALL_AS_READ:
                    builder.setTitle(R.string.exitDialogTitle);
                    builder.setMessage(getString(R.string.markAllAsReadString));
                    builder.setPositiveButton(R.string.exitDialogPositive, new OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                    // TODO Auto-generated method stub
                                    dialog.dismiss();
                                    markAllAsRead();
                            }
                    });
                    builder.setNegativeButton(R.string.exitDialogNegative, new OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                    // TODO Auto-generated method stub
                                    dialog.dismiss();
                            }
                    });
            default:
                    break;
            }
            
            return builder.create();
    }	

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK && 
				event.getRepeatCount() == 0){
			showDialog(DIALOG_EXIT_APP);
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void refreshItem(){
		synchronized (locker) {
			if(isRefreshing){
				return;
			}
			isRefreshing = true;
			titleBar.setProgressBarVisible(true);
			Intent intent = new Intent(this, SyncService.class);
			intent.putExtra(SyncService.AUTO_SYNC, false);
			startService(intent);
		}		
	}	
	private void setGallery(){	
		List<Item> newItems = mItemService.getItemsFromDatabase(mUnReadOnly);
		mFeeds = mItemService.getFeeds(newItems);
		if(mFeeds == null || mFeeds.size()== 0){
			mItemsAdapter.clear();
		}else{
			mItemsAdapter.mItems = mFeeds.get(0).items;
		}
		
		mItemsAdapter.notifyDataSetChanged();
		mFeedAdapter.mFeeds = mFeeds;
		mFeedAdapter.notifyDataSetChanged();
	}
	
	private void clearGallery(){
		mFeeds.clear();
		mFeedAdapter.notifyDataSetChanged();
		mItemsAdapter.clear();
		mItemsAdapter.notifyDataSetChanged();
	}
	
	private void setUnreadItem(){
		if(mUnReadOnly){
			
		}
	}
	
	private void toggleArticles(boolean unreadOnly){
		mUnReadOnly = unreadOnly;
		setGallery();
	}
	
	private void markAllAsRead(){
		if(mFeeds.contains(mFeed)){
        	mFeeds.remove(mFeed);
        	mFeedAdapter.notifyDataSetChanged();
        }
		new Thread(){
			@Override
			public void run() {
				FeedService.markAllAsRead(MainListActivity.this, mFeed);
			}			
		}.start();
		if(mFeeds.isEmpty()){
			mItemsAdapter.mItems = new ArrayList<Item>();
		}
		else if(mSelectedFeed>=mFeeds.size()){
			mItemsAdapter.mItems = mFeeds.get(mFeeds.size()-1).items;
		}else{
			mItemsAdapter.mItems = mFeeds.get(mSelectedFeed).items;					
		}
		mItemsAdapter.notifyDataSetChanged();
	}

}
